<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <!-- <el-select
        v-model="listQuery.associationId"
        style="width: 200px"
        clearable
        class="filter-item"
        placeholder="请选择协会"
      >
        <el-option v-for="(key,index) in associationList" :key="index" :label="key.name" :value="key.id" />
      </el-select> -->
      <el-input v-model="listQuery.name" clearable class="filter-item" style="width: 200px;" placeholder="请输入企业名称" />
      <el-button
        v-permission="['user:enterprise:list']"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter">查找</el-button>
      <!--添加用户-->
      <el-button
        v-permission="['user:enterprise:create']"
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate">添加企业</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      size="small"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row>
      <!-- <el-table-column align="center" label="协会ID" prop="associationId" /> -->

      <el-table-column align="center" label="企业名称" prop="name" />

      <el-table-column align="center" label="法人" prop="legalPerson" />

      <el-table-column align="center" label="企业logo" width="80" prop="logoUrl">
        <template slot-scope="scope">
          <el-popover placement="right" trigger="hover">
            <img :src="scope.row.logoUrl" height="230" >
            <img slot="reference" :src="scope.row.logoUrl" height="23" >
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column align="center" label="营业执照" width="80" prop="businessLicenseUrl">
        <template slot-scope="scope">
          <el-popover placement="right" trigger="hover">
            <img :src="scope.row.businessLicenseUrl" height="230" >
            <img slot="reference" :src="scope.row.businessLicenseUrl" height="23" >
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column align="center" label="简介" prop="introduction">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="showDetail(scope.row)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" label="企业地址" prop="address" />
      <el-table-column align="center" label="联系人" prop="contact"/>
      <el-table-column align="center" label="联系电话" prop="phone"/>
      <el-table-column align="center" label="成立时间" prop="dateOfEstablishment">
        <template slot-scope="scope">{{
          scope.row.dateOfEstablishment | formatHmt
        }}</template>
      </el-table-column>
      <el-table-column align="center" label="备注" prop="remark"/>
      <el-table-column align="center" label="操作" width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-permission="['user:enterprise:update']" type="primary" size="mini" @click="handleUpdate(scope.row)">
            编辑</el-button>
          <el-button v-permission="['user:enterprise:delete']" type="danger" size="mini" @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList" />
    <!-- 查看企业简介 -->
    <div class="introduction">
      <el-dialog :visible.sync="detailDialogVisible" title="企业简介" style="text-align: center;">
        <div class="contentRecord" v-html="introduction" />
      </el-dialog>
    </div>

    <!-- 添加/修改/详情对话框  -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" top="5vh" style="margin-top: -30px;" width="900px">
      <h2 style="margin-top: -10px;">企业基本信息</h2>
      <el-form ref="formData" :model="formData" :rules="rules" label-width="80px" style="margin:10px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入企业名称"/>
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="formData.legalPerson" placeholder="请输入法人"/>
            </el-form-item>
            <el-form-item label="联系人" prop="contact">
              <el-input v-model="formData.contact" placeholder="请输入联系人"/>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="formData.remark" placeholder="请输入备注"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" style="padding-left: 20px;">
            <!-- <el-form-item label="协会" prop="associationId">
              <el-select
                v-model="formData.associationId"
                style="width: 100%;"
                clearable
                class="filter-item"
                placeholder="请选择协会"
              >
                <el-option v-for="(key,index) in associationList" :key="index" :label="key.name" :value="key.id" />
              </el-select>
            </el-form-item> -->
            <el-form-item label="企业地址" prop="address">
              <el-input v-model="formData.address" placeholder="请输入企业地址"/>
            </el-form-item>
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="formData.phone" placeholder="请输入联系电话"/>
            </el-form-item>
            <el-form-item label="成立时间" prop="dateOfEstablishment">
              <el-date-picker
                v-model="formData.dateOfEstablishment"
                type="date"
                placeholder="选择日期" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="企业logo" prop="logoUrl">
              <el-upload
                :action="uploadPath"
                :headers="headers"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeFileUplod"
                class="avatar-uploader"
                accept=".jpg, .jpeg, .png, .gif"
              >
                <img v-if="formData.logoUrl" ref="adImg" :src="formData.logoUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"/>
              </el-upload>
              <div v-if="formData.logoUrl" class="logoUrlIcon">
                <i class="el-icon-zoom-in" style="font-size: 30px;margin-right: 10px;color: #fff;" @click="bigImgLogo"/>
                <i class="el-icon-delete" style="font-size: 30px;color: #fff;" @click="deleteImgLogo"/>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12" style="padding-left: 20px;">
            <el-form-item label="营业执照" prop="businessLicenseUrl">
              <el-upload
                :action="uploadPath"
                :headers="headers"
                :show-file-list="false"
                :on-success="handleBusinessSuccess"
                :before-upload="beforeFileUplod"
                class="avatar-uploader"
                accept=".jpg, .jpeg, .png, .gif"
              >
                <img v-if="formData.businessLicenseUrl" ref="adImg" :src="formData.businessLicenseUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"/>
              </el-upload>
              <div v-if="formData.businessLicenseUrl" class="businessLicenseUrlIcon">
                <i class="el-icon-zoom-in" style="font-size: 30px;margin-right: 10px;color: #fff;" @click="bigImg"/>
                <i class="el-icon-delete" style="font-size: 30px;color: #fff;" @click="deleteImg"/>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="企业简介" prop="introduction">
          <editor :init="editorInit" v-model="formData.introduction" style="min-height: 200px;"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelData">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
    <!-- 企业logo放大框 -->
    <el-dialog :visible.sync="logodDialogVisible" :show-close="false">
      <img :src="formData.logoUrl" width="100%" >
    </el-dialog>
    <!-- 企业营业执照放大框 -->
    <el-dialog :visible.sync="dialogVisible" :show-close="false">
      <img :src="formData.businessLicenseUrl" width="100%" >
    </el-dialog>
  </div>
</template>

<script>
import { listEnterprise, createEnterprise, updateEnterprise, deleteEnterprise, associationSelect, richTextEnterprise, queryEnterprise } from '@/api/enterprise'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import Editor from '@tinymce/tinymce-vue'
import { uploadPath, beforeFileUplod, createStorage } from '@/api/storage'
import { getToken } from '@/utils/auth'

export default {
  name: 'Enterprise',
  components: { Pagination, Editor },
  data() {
    return {
      uploadPath,
      beforeFileUplod,
      associationList: [],
      list: [],
      introduction: '',
      total: 0,
      listLoading: true,
      listQuery: {
        pageNo: 1,
        limit: 20,
        associationId: undefined,
        name: undefined
      },
      formData: {
        dateOfEstablishment: undefined,
        name: undefined,
        phone: undefined,
        legalPerson: undefined,
        contact: undefined,
        address: undefined,
        remark: undefined,
        logoUrl: undefined,
        introduction: undefined,
        businessLicenseUrl: undefined
      },
      detailDialogVisible: false,
      textMap: { update: '编辑', create: '创建' },
      dialogFormVisible: false,
      dialogStatus: '',
      // 图片放大框
      dialogVisible: false,
      logodDialogVisible: false,
      rules: {
        name: [{ required: true, message: '企业名称不能为空', trigger: 'blur' }],
        phone: [{ required: true, message: '联系电话不能为空', trigger: 'blur' }, { pattern: /^1[3456789]\d{9}$/, message: '请输入正确电话' }],
        legalPerson: [{ required: true, message: '法人不能为空', trigger: 'blur' }],
        contact: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
        dateOfEstablishment: [{ required: true, message: '请选择日期', trigger: 'blur' }],
        address: [{ required: true, message: '企业地址不能为空', trigger: 'blur' }],
        logoUrl: [{ required: true, message: '请选择图片', trigger: 'blur' }],
        businessLicenseUrl: [{ required: true, message: '请选择图片', trigger: 'blur' }],
        introduction: [{ required: true, message: '企业简介不能为空', trigger: 'blur' }]
      },
      editorInit: {
        language: 'zh_CN',
        convert_urls: false,
        plugins: ['advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'],
        toolbar: ['searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample', 'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'],
        images_upload_handler: function(blobInfo, success, failure) {
          const formData = new FormData()
          formData.append('file', blobInfo.blob())
          createStorage(formData).then(res => {
            success(res.data.url)
          }).catch(() => {
            failure('上传失败，请重新上传')
          })
        }
      }
    }
  },
  computed: {
    headers() {
      return {
        ADMINTOKEN: getToken()
      }
    }
  },
  created() {
    this.getList()
    this.getAssociationList()
  },
  methods: {
    // 获取协会下拉框
    getAssociationList() {
      associationSelect().then(response => {
        this.associationList = response.data.data
      })
    },
    getList() {
      this.listLoading = true
      listEnterprise(this.listQuery)
        .then(response => {
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    resetForm() {
      this.formData = {
        dateOfEstablishment: undefined,
        name: undefined,
        phone: undefined,
        legalPerson: undefined,
        contact: undefined,
        address: undefined,
        remark: undefined,
        introduction: undefined,
        logoUrl: undefined,
        businessLicenseUrl: undefined
      }
    },
    // 查看公司简介
    showDetail(row) {
      richTextEnterprise(row.id)
        .then(response => {
          this.detailDialogVisible = true
          this.introduction = response.data.data
        })
        .catch(response => {
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    cancelData() {
      this.dialogFormVisible = false
      this.resetForm()
    },
    handleCreate() {
      this.resetForm()
      this.formData.introduction = ''
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['formData'].clearValidate()
      })
    },
    createData() {
      this.$refs['formData'].validate(valid => {
        if (valid) {
          createEnterprise(this.formData)
            .then(response => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '创建成功'
              })
              this.getList()
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleUpdate(row) {
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      queryEnterprise(row.id)
        .then(res => {
          this.formData = res.data.data
        })
      this.$nextTick(() => {
        this.$refs['formData'].clearValidate()
      })
    },
    updateData() {
      this.$refs['formData'].validate(valid => {
        if (valid) {
          updateEnterprise(this.formData)
            .then(() => {
              for (const v of this.list) {
                if (v.id === this.formData.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.formData)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新用户成功'
              })
              this.getList()
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleDelete(row) {
      const h = this.$createElement
      this.$confirm(this.message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        message: h('p', null, [
          h('span', null, '此操作将永久删除 '),
          h('i', { style: 'color: red' }, row.name),
          h('span', null, ' ,是否继续? ')
        ])
      }).then(() => {
        deleteEnterprise(row.id)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            this.getList()
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      }).catch(() => {
        return false
      })
    },
    // 上传企业logo
    handleAvatarSuccess(res, file) {
      this.formData.logoUrl = res.url
    },
    // 上传营业执照
    handleBusinessSuccess(res, file) {
      this.formData.businessLicenseUrl = res.url
    },
    // 企业logo图放大
    bigImgLogo() {
      this.logodDialogVisible = true
    },
    // 营业执照放大
    bigImg() {
      this.dialogVisible = true
    },
    // 企业logo图删除
    deleteImgLogo() {
      this.formData.logoUrl = ''
    },
    // 营业执照删除
    deleteImg() {
      this.formData.businessLicenseUrl = ''
    }
  }
}
</script>
<style lang="scss" scoped>
.contentRecord{
  ::v-deep img {
    width: 100%;
  }
}
  .el-dialog{
    -webkit-box-shadow: none !important;
  }

</style>
<style>
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .logoUrlIcon {
  position: absolute;
  top: 2px;
  z-index: 999;
  background-color: rgba(0, 0, 0, 0.3);
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}
.businessLicenseUrlIcon{
  position: absolute;
  top: 2px;
  z-index: 999;
  background-color: rgba(0, 0, 0, 0.3);
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}
  .el-dialog__body{
    padding: 20px 20px 0;
  }
  .introduction .el-dialog{
    padding-bottom: 20px;
    width: 700px;
  }
</style>

